<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>getSnapshotBeforeUpdate的使用场景</title>
    <style>
      .list{
        width: 200px;
        height: 150px;
        background-color: cadetblue;
        overflow: auto;
      }
      .news{
        height: 30px;
      }
    </style>

  </head>

  <body>
    <div id="test"></div>

    <script type="text/javascript" src="../js/17.0.1/react.development.js"></script>
    <script
      type="text/javascript"
      src="../js/17.0.1/react-dom.development.js"
    ></script>
    <script type="text/javascript" src="../js/17.0.1/babel.min.js"></script>

    <script type="text/babel">

      class NewList extends React.Component {

        state = {newsArr:[]}

        componentDidMount(){
          setInterval(() =>{
            //获取原来状态
            const {newsArr} = this.state
            const news = '新闻'+(newsArr.length+1)
            this.setState({newsArr:[news,...newsArr]})
          },1000)

        }

        getSnapshotBeforeUpdate(){
          return this.refs.list.scrollHeight
        }

        componentDidUpdate(preProps,preState,heigth){
          this.refs.list.scrollTop += this.refs.list.scrollHeight - heigth
        }

        render(){
          return(
            <div className="list" ref='list'>
              {
                this.state.newsArr.map((news,index) => {
                  return <div key="index" className='news'>{news}</div>
                })
              }
            </div>
          )
        }

      }

      ReactDOM.render(<NewList />, document.getElementById("test"));
    </script>
  </body>
</html>
